package org.dev_common.json;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Jacksons {
    private static Logger logger = LoggerFactory.getLogger(Jacksons.class);

    private static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        // todo more settings here
    }

    public static <T> T parse(String json, Class<T> clazz) throws Exception {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            logger.error("convert json to bean failed", e);
            throw e;
        }
    }

    public static <T> T parse(String json, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            logger.error("convert json to bean failed", e);
            return null;
        }
    }

    public static <T> String string(T bean) throws Exception {
        try {
            return objectMapper.writeValueAsString(bean);
        } catch (Exception e) {
            logger.error("convert bean to json failed", e);
            throw e;
        }
    }

    public static byte[] bytes(Object bean) throws Exception {
        try {
            return objectMapper.writeValueAsBytes(bean);
        } catch (Exception e) {
            logger.error("convert bean to json bytes failed", e);
            throw e;
        }
    }
}
